<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 删除按钮 -->
			<cl-multi-delete-btn />
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table" />
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
</template>

<script lang="tsx" setup>
defineOptions({
	name: 'advertisement-index'
});

import { useCrud, useTable, useUpsert, useSearch } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';

const { service } = useCool();
const { t } = useI18n();

// cl-upsert
const Upsert = useUpsert({
	items: [
		{
			prop: 'advertisementType',
			label: t('类型'),
			required: true,
			value: 0,
			component: {
				name: 'el-radio-group',
				options: [
					{
						label: t('轮播图'),
						value: 0
					},
					{
						label: t('通告'),
						value: 1
					}
				]
			}
		},
		{
			label: t('内容'),
			prop: 'advertisementName',
			required: true,
			span: 24,
			component: {
				name: 'el-input'
			},
			hidden: ({ scope }) => {
				return scope.advertisementType === 0;
			}
		},
		{
			label: t('广告图片'),
			prop: 'advertisementImg',
			required: true,
			component: {
				name: 'cl-upload',
				props: {
					text: t('选择图片')
				}
			},
			span: 12,
			hidden: ({ scope }) => {
				return scope.advertisementType === 1;
			}
		}
	]
});

// cl-table
const Table = useTable({
	columns: [
		{ type: 'selection' },
		{
			label: t('类型'),
			prop: 'advertisementType',
			minWidth: 120,
			dict: [
				{
					label: '轮播图',
					value: 0,
					type: 'success'
				},
				{
					label: '通告',
					value: 1,
					type: 'danger'
				}
			]
		},
		{
			label: t('广告名称'),
			prop: 'advertisementName',
			minWidth: 120
		},
		{
			label: t('广告图片'),
			prop: 'advertisementImg',
			minWidth: 120,
			formatter: (row, column, value, index) => {
				// 通过判断后缀名判断是否为图片
				if (!value) return '';
				if (value.endsWith('.jpg') || value.endsWith('.png') || value.endsWith('.gif')) {
					return <img src={value} width="100" height="100" />;
				} else {
					// 否则是视频
					return <video src={value} width="100" height="100" controls />;
				}
			}
		},
		{
			label: t('创建时间'),
			prop: 'createTime',
			minWidth: 170,
			sortable: 'desc',
			component: { name: 'cl-date-text' }
		},
		{ type: 'op', buttons: ['edit', 'delete'] }
	]
});

// cl-search
const Search = useSearch();

// cl-crud
const Crud = useCrud(
	{
		service: service.advertisement.index
	},
	app => {
		app.refresh();
	}
);

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}
</script>
